// 增加减少商品数量
import { computed, toRefs } from 'vue'
import { useStore } from 'vuex'

export function useGoodsCountEffect (shopId) {
  const store = useStore()
  const { cartList } = toRefs(store.state)

  const handldGoodsCount = (shopId, goodsId, goodsInfo, num) => {
    const GoodsInfo = { shopId, goodsId, goodsInfo, num }
    store.commit('changeGoodsInfo', GoodsInfo)
  }

  // 获取列表中选中的商品信息
  const goodsInfo = computed(() => {
    const productInfo = cartList.value?.[shopId] || []
    return productInfo
  })

  // computed 计算属性返回一个响应式 ref 对象
  // computed 计算属性动态计算 选中的商品价格 price，数量 counts
  const computedResult = computed(() => {
    const goods = cartList.value?.[shopId]
    const result = { counts: 0, price: 0 }
    if (goods) {
      for (const i in goods) {
        const product = goods[i]
        if (product.checked) {
          result.counts += product.count
          result.price += (product.price * product.count)
        }
      }
    }
    result.price = result.price.toFixed(2)
    return result
  })

  return { cartList, goodsInfo, computedResult, handldGoodsCount }
}
